package com.example.donghuihui.androidframe.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.donghuihui.androidframe.R;

/**
 * 自定义Toast显示工具类
 */
@SuppressLint("InflateParams")
public class ToastUtil {
    private static Toast toast = null;
    private static TextView tv = null;

    public static void showToast(Context context, int stringId) {
        try {
            show(context, context.getResources().getString(stringId), Toast.LENGTH_SHORT);
        } catch (Exception e) {
            e.printStackTrace();
            show(context, "error", Toast.LENGTH_SHORT);
        }
    }

    public static void showToast(Context context, int stringId, int duration) {
        try {
            show(context, context.getResources().getString(stringId), duration);
        } catch (Exception e) {
            show(context, "error", duration);
        }
    }

    public static void showToast(Context context, String text) {
        show(context, text, Toast.LENGTH_SHORT);
    }

    public static void showToast(Context context, String text, int duration) {
        show(context, text, duration);
    }

    private static void show(Context context, String text, int duration) {
        if (context == null) {
            return;
        }
        LayoutInflater mInflater = LayoutInflater.from(context);
        if (toast == null) {
            View v = mInflater.inflate(R.layout.include_toast, null);
            tv = (TextView) v.findViewById(R.id.toast_tv_content);
            toast = new Toast(context);
            toast.setView(v);
        }
        toast.setDuration(duration);
        tv.setText(text);
        toast.show();
    }
}
